import { isInArray } from "@/utils"
import { random } from "lodash"
import { resourceComDispatch } from "../local/constant"
import { RecognizeLab } from "../local/resource"

/* 框架控制相关 */
export default {
    /* 控制房间 */
    frame:{
        add(roomName:string,layout:string):string{
            if (!Memory.ControlPlan) Memory.ControlPlan = {}
            if (isInArray(Object.keys(Memory.ControlPlan),roomName))
            return `[frame] 房间${roomName}已经存在ControlPlan里了！`
            Memory.ControlPlan[roomName] = {name:roomName,layoutPlan:layout}
            return `[frame] 房间${roomName}已经成功添加进ControlPlan里！布局计划为${layout}`
        },
        remove(roomName:string):string{
            if (!Memory.ControlPlan[roomName]) return `[frame] ControlPlan里没有发现房间${roomName}`
            delete Memory.ControlPlan[roomName] 
            return `[frame] ControlPlan里已经删除房间${roomName}`
        },
        show():string{
            var str = '[frame] 名单:'
            for (var i in Memory.ControlPlan)
            {
                str +=  ` ${i} + layoutPlan:${Memory.ControlPlan[i].layoutPlan}`
                
            }
            return str
        },
        /* 中心点设定 */
        center(roomName:string,x:number,y:number):string{
            var myRoom = Game.rooms[roomName]
            if (!myRoom) return `[frame] 未找到房间${roomName},请确认房间!`
            myRoom.memory.center_x = x
            myRoom.memory.center_y = y
            return `[frame] 房间${roomName}的中心点已经设置为${x}-${y}!`
        },
        /* 删除建筑 */
        del(roomName:string,x:number,y:number,mold:BuildableStructureConstant):string{
            var myRoom = Game.rooms[roomName]
            if (!myRoom) return `[frame] 未找到房间${roomName},请确认房间!`
            var thisPosition:RoomPosition = new RoomPosition(x,y,roomName)
            if (thisPosition.GetStructure(mold))
                {myRoom.unbindMemory(mold,x,y);return `[frame] 房间${roomName}已经执行delStructure命令!`}
            return `[frame] 房间${roomName}未找到相应建筑!`
        },
        defend(roomName:string,class_:string,x:number,y:number,range:number):string
        {
            if (!Memory.ControlPlan[roomName]) return `[frame] ControlPlan里没有发现房间${roomName}`
            Memory.ControlPlan[roomName].defendPlan = {class_,x,y,range}
            return `[frame] 房间${roomName}的defendPlan: class_:${class_};x:${x};y:${y};range:${range}`
        },
        defendshow(roomName):string{
            if (!Memory.ControlPlan[roomName]) return `[frame] ControlPlan里没有发现房间${roomName}`
            var defendData =  Memory.ControlPlan[roomName].defendPlan
            if (!defendData) return `[frame] 房间${roomName}不存在防御数据!`
            return `[frame] 房间${roomName}的defendPlan: class_:${defendData.class_};x:${defendData.x};y:${defendData.y};range:${defendData.range}`
        }
    },
    /* 爬虫孵化 */
    spawn:{
        show(roomName:string):string{
            if (!global.CreepNumData) return `[spawn] 未发现CreepNumData！`
            if (!Game.rooms[roomName]) return `[spawn] 房间${roomName}不是所属房间！`
            var str = `[spawn] 房间${roomName}的CreepNumData数据:\n`
            for (var i in global.CreepNumData[roomName])
            {
                str += `role:${i} num:${global.CreepNumData[roomName][i].num}\n`
            }
            return str
        },
        set(roomName:string,role:string,num:number):string{
            if (!global.CreepNumData) return `[spawn] 未发现CreepNumData！`
            if (!Game.rooms[roomName]) return `[spawn] 房间${roomName}不是所属房间！`
            if (!Game.rooms[roomName][role]) return `[spawn] 房间${roomName}的孵化列表里未发现角色${role}！`
            if (!Game.rooms[roomName].memory.spawnData)  Game.rooms[roomName].memory.spawnData = {}
            Game.rooms[roomName].memory.spawnData[role] = num
            return `[spawn] 房间${roomName}的孵化列表里角色${role}的数量已经调整为${num}！`
        },
        /* 取消房间里某个角色的数量信息 */
        remove(roomName:string,role?:string):string{
            if (!Game.rooms[roomName]) return `[spawn] 房间${roomName}不是所属房间！`
            if (!Game.rooms[roomName].memory.spawnData)  Game.rooms[roomName].memory.spawnData = {}
            if (!role) 
            {
                Game.rooms[roomName].memory.spawnData = {}
                return `[spawn] 已经清空房间${roomName}的所有爬虫数量信息！`
            }
            if (!Game.rooms[roomName].memory.spawnData[role]) return `[spawn] 房间${roomName}的孵化列表里未发现角色${role}！`
            delete Game.rooms[roomName].memory.spawnData[role]
            return` [spawn] 已经清空房间${roomName}的爬虫${role}数量信息！`
        }
    },
    /* lab */
    lab:{
            /* 寻找房间名/数字的旗帜，初始化一个房间的lab合成配置，没有配置的房间不可以进行合成任务*/
        init(roomName:string,raw1:number,raw2:number,com:number[]):string{
            var myRoom = Game.rooms[roomName]
            if (!myRoom) return `[lab] 未找到房间${roomName},请确认房间！`
            /* 初始化 原先配置清零 */
            myRoom.memory.StructureIdData.labInspect=  {}
            var temp1 = [raw1].concat([raw2])
            var temp2 = temp1.concat(com)
            for (var i of temp2)
            {
                if (!Game.flags[`${roomName}/${i}`])
                    return `[lab] 未发现旗帜${roomName}/${i}！`
                if (!Game.flags[`${roomName}/${i}`].pos.GetStructure('lab'))
                    return `[lab] 旗帜${roomName}/${i}下未发现lab！`

            }
            var result = `[lab] 房间${roomName}已经完成lab配置，详细配置如下：\n`
            for (var b in temp2)
            {
                var flag = Game.flags[`${roomName}/${temp2[b]}`]
                var strucLab = flag.pos.GetStructure('lab')
                if (b == '0')
                {
                    myRoom.memory.StructureIdData.labInspect['raw1'] = strucLab.id
                    result += `raw1:${strucLab.id}\n`
                }
                else if (b == '1')
                {
                    myRoom.memory.StructureIdData.labInspect['raw2'] = strucLab.id
                    result += `raw2:${strucLab.id}\n`
                }
                else
                {
                    if (!myRoom.memory.StructureIdData.labInspect['com'])
                    {
                        myRoom.memory.StructureIdData.labInspect['com'] = []
                        result += `com:\n`
                    }
                    if (!isInArray(myRoom.memory.StructureIdData.labInspect['com'],strucLab.id))
                        myRoom.memory.StructureIdData.labInspect['com'].push(strucLab.id)
                        result += `${strucLab.id}\n`
                }
                
            }
            return result
            
            
        },
        compound(roomName:string,res:ResourceConstant,num:number):string{
            var myRoom = Game.rooms[roomName]
            if (!myRoom) return `[lab] 未找到房间${roomName},请确认房间！`
            var thisTask = myRoom.Public_Com(num,res)
            if (thisTask === null) return `[lab] 挂载合成任务失败!`
            if (myRoom.AddMisson(thisTask))
            return `[lab] 房间${roomName}合成${res}任务挂载成功! ${thisTask.data.raw1} + ${thisTask.data.raw2} = ${res}`
            else
            return `[lab] 房间${roomName}挂载合成任务失败！`
        },
        Ccompound(roomName:string):string{
            var myRoom = Game.rooms[roomName]
            if (!myRoom) return `[lab] 未找到房间${roomName},请确认房间!`
            for (var r in myRoom.memory.Misson)
            for (var i of myRoom.memory.Misson[r])
            {
                if (i.name == '资源合成')
                {
                    if(myRoom.DeleteMisson(i.id))return `[lab] 房间${roomName}删除资源合成任务成功!`
                }
            }   
            return `[lab] 房间${roomName}删除资源合成任务失败!`  
        },
        dispatch(roomName:string,res:ResourceConstant,num:number):string{
            var myRoom = Game.rooms[roomName]
            if (!myRoom) return `[lab] 未找到房间${roomName},请确认房间!`
            if (!resourceComDispatch[res]) return `不存在资源${res}！`
            if (myRoom.memory.ComDispatchData.length > 0) return `[lab] 房间${roomName} 已经存在资源合成调度数据`
            myRoom.memory.ComDispatchData = []
            for (var i of resourceComDispatch[res])
            {
                myRoom.memory.ComDispatchData.push({res:i,num:num,dispatch_num:num})
            }
            return `[lab] 已经修改房间${roomName}的资源调度数据，为${resourceComDispatch[res]}，数量：${num}`
        },
        Cdispatch(roomName:string):string{
            var myRoom = Game.rooms[roomName]
            if (!myRoom) return `[lab] 未找到房间${roomName},请确认房间!`
            myRoom.memory.ComDispatchData = []
            return `[lab] 已经修改房间${roomName}的资源调度数据，为{}.本房见现已无资源合成调度`
        },
        /* 更改资源合成调度数据 */
        dispatchNum(roomName:string,res:ResourceConstant,num:number):string{
            var myRoom = Game.rooms[roomName]
            if (!myRoom) return `[lab] 未找到房间${roomName},请确认房间!`
            if (myRoom.memory.ComDispatchData[myRoom.memory.ComDispatchData.length].res != res) return `[lab] 资源不符合！${res}的资源合成调度数据更改失败`
            for (var i of myRoom.memory.ComDispatchData)
            {
                i.dispatch_num = num
            }
            return `[lab] 已经修改房间${roomName}的资源调度数据，为${resourceComDispatch[res]}，数量：${num}`
        },
        Ainit(roomName:string):string{
            var myRoom = Game.rooms[roomName]
            if (!myRoom) return `[lab] 未找到房间${roomName},请确认房间!`
            /* 初始化 原先配置清零 */
            myRoom.memory.StructureIdData.labInspect=  {}
            let result = RecognizeLab(roomName)
            if (result == null) return `[lab] 房间${roomName}初始化合成lab信息失败!`
            myRoom.memory.StructureIdData.labInspect['raw1'] = result.raw1
            myRoom.memory.StructureIdData.labInspect['raw2'] = result.raw2
            myRoom.memory.StructureIdData.labInspect['com'] = result.com
            let str = ''
            str += `[lab] 房间${roomName}初始化lab信息成功!\n`
            str += `底物lab:\n${result.raw1}\n${result.raw2}\n`
            str += "合成lab:\n"
            for (let i of result.com) str += `${i}\n`
            return str
        },

        
    },
    /* 临时测试指令 */
    debug:{
        /* 搬运指令 */
        carry(sR:string,sX:number,sY:number,tR:string,tX:number,tY:number,rType:ResourceConstant,num?:number):string{
            var myRoom = Game.rooms[sR]
            if (!myRoom) return `[debug] 未找到房间${sR},请确认房间!`
            var thisTask:MissionModel = 
            {
                name :'物流运输',
                CreepBind:{'manage':{num:1,bind:[]}},
                range:'Creep',
                delayTick:60,
                data:{
                    sourceRoom:sR,
                    sourcePosX:sX,
                    sourcePosY:sY,
                    targetRoom:tR,
                    targetPosX:tX,
                    targetPosY:tY,
                    rType:rType,
                }
            }
            if (num) thisTask.data.num = num
            if (myRoom.AddMisson(thisTask))
            return `[debug] 房间${sR}物流运输任务挂载成功!`
        },
        Ccarry(roomName:string):string{
            var myRoom = Game.rooms[roomName]
            if (!myRoom) return `[debug] 未找到房间${roomName},请确认房间!`
            for (var r in myRoom.memory.Misson)
            for (var i of myRoom.memory.Misson[r])
            {
                if (i.name == '物流运输')
                {
                    if(myRoom.DeleteMisson(i.id))return `[debug] 房间${roomName}删除物流运输任务成功!`
                }
            }   
            return `[debug] 房间${roomName}删除物流运输任务失败!`  
        },
        /* 资源发送指令 */
        send(sR:string,dR:string,rType:ResourceConstant,num:number):string{
            var myRoom = Game.rooms[sR]
            if (!myRoom) return `[debug] 未找到房间${sR},请确认房间!`
            var thisTask = myRoom.Public_Send(dR,rType,num)
            if (myRoom.AddMisson(thisTask))
            return `[debug] 房间${sR}资源传送任务挂载成功!`
        },
        Csend(roomName:string):string{
            var myRoom = Game.rooms[roomName]
            if (!myRoom) return `[debug] 未找到房间${roomName},请确认房间!`
            for (var r in myRoom.memory.Misson)
            for (var i of myRoom.memory.Misson[r])
            {
                if (i.name == '资源传送')
                {
                    if(myRoom.DeleteMisson(i.id))return `[debug] 房间${roomName}删除资源传送任务成功!`
                }
            }   
            return `[debug] 房间${roomName}删除资源传送任务失败!`  
        },
        /* 测试 */
        buy(roomName:string,rType:ResourceConstant,num:number,range:number,max?:number):string{
            var myRoom = Game.rooms[roomName]
            if (!myRoom) return `[debug] 未找到房间${roomName},请确认房间!`
            var thisTask = myRoom.Public_Buy(rType,num,range,max?max:35)
            if (thisTask === null) return `[debug] buy指令错误`
            if (myRoom.AddMisson(thisTask))
            return `[debug] 房间${roomName}资源${rType}购买任务挂载成功! 价格区间:${range},数量${num}!`
            return `[debug] 资源购买任务挂载失败！`
            
        },
        Cbuy(roomName:string):string{
            var myRoom = Game.rooms[roomName]
            if (!myRoom) return `[debug] 未找到房间${roomName},请确认房间!`
            for (var r in myRoom.memory.Misson)
            for (var i of myRoom.memory.Misson[r])
            {
                if (i.name == '资源购买')
                {
                    if(myRoom.DeleteMisson(i.id))return `[debug] 房间${roomName}删除资源购买任务成功!`
                }
            }   
            return `[debug] 房间${roomName}删除资源购买任务失败!`  
        },
        sell(roomName:string,rType:ResourceConstant,num:number,type:'deal'|'order',price?:number,unit?:number):string{
            var myRoom = Game.rooms[roomName]
            if (!myRoom) return `[debug] 未找到房间${roomName},请确认房间!`
            if (!myRoom.memory.market) myRoom.memory.market = {'deal':[],'order':[]}
            if (type == 'deal')
            {
                if (!myRoom.memory.market['deal']) myRoom.memory.market['deal'] = []
                myRoom.memory.market['deal'].push({rType:rType,num:num})
                return `[debug] 已经挂载${rType}的deal卖单,数量为${num}`
            }
            else
            {
                if (!myRoom.memory.market['order']) myRoom.memory.market['order'] = []
                myRoom.memory.market['order'].push({rType:rType,num:num,price:price?price:10,unit:unit?unit:1000})
                return `[debug] 已经挂载${rType}的order卖单,数量为${num},价格${price}`
            }
        },
        sign(roomName:string,disRoom:string,shard:shardName,words:string):string{
            var myRoom = Game.rooms[roomName]
            if (!myRoom) return `[debug] 未找到房间${roomName},请确认房间!`
            var thisTask = myRoom.Public_Sign(1,disRoom,shard,words)
            if (myRoom.AddMisson(thisTask)) return `[debug] 签名任务挂载成功!`
            return `[debug] 签名任务挂载失败!`
        },
    },

    upgrade:{
        rush(roomName:string,num:number = 1,rType?:ResourceConstant):string{
            var myRoom = Game.rooms[roomName]
            if (!myRoom) return `[lab] 未找到房间${roomName},请确认房间！`
            if (rType)
                var thisTask = myRoom.Public_level(num,rType)
            else
                var thisTask = myRoom.Public_level(num,'GH',true)
            if (thisTask === null) return `[upgrade] 房间${roomName} 控制冲级任务挂载失败!`
            if (myRoom.AddMisson(thisTask))
            {
                return `[upgrade] 房间${roomName} 控制冲级任务挂载成功! 数量${num},rType:${rType}`
            }
            return `[upgrade] 房间${roomName} 控制冲级任务挂载失败!`

        },
        Crush(roomName:string):string{
            var myRoom = Game.rooms[roomName]
            if (!myRoom) return `[debug] 未找到房间${roomName},请确认房间!`
            for (var r in myRoom.memory.Misson)
            for (var i of myRoom.memory.Misson[r])
            {
                if (i.name == '控制冲级')
                {
                    if(myRoom.DeleteMisson(i.id))return `[debug] 房间${roomName}删除控制冲级任务成功!`
                }
            }   
            return `[debug] 房间${roomName}删除控制冲级任务失败!` 
        },
        num(roomName:string,num:number):string{
            var myRoom = Game.rooms[roomName]
            if (!myRoom) return `[debug] 未找到房间${roomName},请确认房间!`
            for (var r in myRoom.memory.Misson)
            for (var i of myRoom.memory.Misson[r])
            {
                if (i.name == '控制冲级')
                {
                    i.data.num = num
                    i.CreepBind['level'].num = num
                    return `[upgrade] 房间${roomName}控制冲级任务数量数据更改成功，为${num}`
                }
            }   
            return `[debug] 房间${roomName}改变控制冲级任务数量数据失败!` 
        }
    },
    support:{
        BoostBuild(roomName:string,disRoom:string,Bnum:number,Cnum:number,shard:shardName = Game.shard.name as shardName):string{
            var myRoom = Game.rooms[roomName]
            if (!myRoom) return `[support] 未找到房间${roomName},请确认房间!`
            var thisTask = myRoom.Public_BoostBuild(disRoom,shard,Bnum,Cnum)
            if (myRoom.AddMisson(thisTask)) return `[support] 援建一体任务挂载成功! ${Game.shard.name}/${roomName} -> ${shard}/${disRoom}`
            return `[support] 援建一体挂载失败!`
        },
        CBoostBuild(roomName:string,disRoom:string,shard:string):string{
            var myRoom = Game.rooms[roomName]
            if (!myRoom) return `[support] 未找到房间${roomName},请确认房间!`
            for (var i of myRoom.memory.Misson['Creep'])
            {
                if (i.name == '援建一体' && i.data.disRoom == disRoom && i.data.shard == shard)
                {
                    if (myRoom.DeleteMisson(i.id))
                    return `[support] 删除去往${shard}/${disRoom}的援建一体任务成功！`
                }
            }
            return `[support] 删除去往${shard}/${disRoom}的援建一体任务失败！`
        },
        BoostUpgrade(roomName:string,disRoom:string,Bnum:number,shard:shardName = Game.shard.name as shardName):string{
            var myRoom = Game.rooms[roomName]
            if (!myRoom) return `[support] 未找到房间${roomName},请确认房间!`
            var thisTask = myRoom.Public_HelpUpgrade(disRoom,shard,Bnum)
            if (myRoom.AddMisson(thisTask)) return `[support] 协助升级任务挂载成功! ${Game.shard.name}/${roomName} -> ${shard}/${disRoom}`
            return `[support] 协助升级挂载失败!`
        },
        CBoostUpgrade(roomName:string,disRoom:string,shard:string):string{
            var myRoom = Game.rooms[roomName]
            if (!myRoom) return `[support] 未找到房间${roomName},请确认房间!`
            for (var i of myRoom.memory.Misson['Creep'])
            {
                if (i.name == '协助升级' && i.data.disRoom == disRoom && i.data.shard == shard)
                {
                    if (myRoom.DeleteMisson(i.id))
                    return `[support] 删除去往${shard}/${disRoom}的协助升级任务成功！`
                }
            }
            return `[support] 删除去往${shard}/${disRoom}的协助升级任务失败！`
        },
        BoostRear(roomName:string,disRoom:string,Num:number,shard:shardName,time:number = 1000,rType:ResourceConstant = 'energy'):string{
            var myRoom = Game.rooms[roomName]
            if (!myRoom) return `[support] 未找到房间${roomName},请确认房间!`
            var thisTask = myRoom.Public_HelpRear(disRoom,shard,Num,rType,time)
            if (myRoom.AddMisson(thisTask)) return `[support] 后勤协助任务挂载成功! ${Game.shard.name}/${roomName} -> ${shard}/${disRoom} resource ${rType}  time:${time}`
            return `[support] 后勤协助挂载失败!`
        },
        CBoostRear(roomName:string,disRoom:string,shard:string):string{
            var myRoom = Game.rooms[roomName]
            if (!myRoom) return `[support] 未找到房间${roomName},请确认房间!`
            for (var i of myRoom.memory.Misson['Creep'])
            {
                if (i.name == '后勤协助' && i.data.disRoom == disRoom && i.data.shard == shard)
                {
                    if (myRoom.DeleteMisson(i.id))
                    return `[support] 删除去往${shard}/${disRoom}的后勤协助任务成功！`
                }
            }
            return `[support] 删除去往${shard}/${disRoom}的后勤协助任务失败！`
        },
    },
    aio:{
        attack(roomName:string,disRoom:string,CreepNum:number,shard:shardName,time:number = 1000,body?:number[]):string{
            var myRoom = Game.rooms[roomName]
            if (!myRoom) return `[support] 未找到房间${roomName},请确认房间!`
            var thisTask = myRoom.Publid_Aio(disRoom,shard,CreepNum,time,body?body:null)
            if (myRoom.AddMisson(thisTask)) return `[support] 攻防一体任务挂载成功! ${Game.shard.name}/${roomName} -> ${shard}/${disRoom}`
            return `[support] 攻防一体挂载失败!`
        },
        Cattack(roomName:string,disRoom:string,shard:shardName):string{
            var myRoom = Game.rooms[roomName]
            if (!myRoom) return `[support] 未找到房间${roomName},请确认房间!`
            for (var i of myRoom.memory.Misson['Creep'])
            {
                if (i.name == '攻防一体' && i.data.disRoom == disRoom && i.data.shard == shard)
                {
                    if (myRoom.DeleteMisson(i.id))
                    return `[support] 删除去往${shard}/${disRoom}的攻防一体任务成功！`
                }
            }
            return `[support] 删除去往${shard}/${disRoom}的攻防一体任务失败！`
        }
    },
    power:{
        switch(roomName:string):string{
            var myRoom = Game.rooms[roomName]
            if (!myRoom) return `[debug] 未找到房间${roomName},请确认房间!`
            myRoom.memory.StopPower = !myRoom.memory.StopPower
            return `[power] 房间${roomName}的power升级已经设置为${myRoom.memory.StopPower}`
        }
    },
    
}